<template>
  <div class="app-container">
    <el-form inline>
      <el-form-item label="内部订单编号：">
        <el-input
          v-model.trim="query.innerCode"
          placeholder="请输入内部订单编号"
        />
      </el-form-item>

      <el-form-item label="图号：">
        <el-input v-model.trim="query.picCode" placeholder="请输入图号" />
      </el-form-item>

      <el-form-item label="名称：">
        <el-input v-model.trim="query.picName" placeholder="请输入名称" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="small" @click="selected"
          >查询</el-button
        >
        <el-button plain size="small" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="app-container">
      <el-table
        border
        :data="list"
        v-loading="listLoading"
        :header-row-style="{
          'background-color': '#E6E6E6',
          'font-weight': 'bold',
          color: '#333'
        }"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
      >
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="orderCode"
          label="内部订单编号"
          width="160px"
        />

        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="picCode"
          label="图号"
          width="180px"
        />

        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="picName"
          label="名称"
        />

        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="amount"
          label="数量"
        />

        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="deliveryTime"
          label="交货日期"
        />

        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="isCompleteCraft"
          label="是否完成编排工艺">
          <template slot-scope="scope">
            <p v-if="scope.row.isCompleteCraft">是</p>
            <p v-if="!scope.row.isCompleteCraft">否</p>
          </template>
        </el-table-column>

        <el-table-column
          show-overflow-tooltip
          align="center"
          label="状态"
          prop="statusName"
        />

        <!-- <el-table-column
          show-overflow-tooltip
          align="center"
          prop="picName"
          label="作业时间"
        /> -->

        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="cal"
          label="操作"
          width="300px"
        >
          <template slot-scope="scope">
            <el-button type="text" plain @click="arrageAction(scope.row)"
              >编排工艺</el-button
            >
            <el-button
              type="text"
              plain
              @click="showDetail(scope.row.productId)"
              >查看</el-button
            >

            <el-button
              type="text"
              plain
              @click="detailAction(scope.row.productId)"
              >删除工艺</el-button
            >

            <el-button type="text" size="mini" plain @click="seePaper(scope.row)"
              >查看图纸</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="query.page"
        :total="total"
        :page-size="query.limit"
        style="padding: 30px 0; text-align: end"
        layout="total, prev, pager, next,jumper"
        @current-change="fetchData"
      />
    </div>

    <!-- 详情 -->
    <el-dialog title="详情" :visible.sync="detailModal.show">
      <div class="the-detail-dialog-content" v-loading="detailModal.loading">
        <el-descriptions
          v-for="(detail, index) in detailModal.list"
          :title="getStepText(detail.step)"
          :key="index"
          :column="1"
        >
          <el-descriptions-item label="工艺名称">{{
            detail.craft
          }}</el-descriptions-item>
          <el-descriptions-item label="组长">{{
            detail.chargemanName
          }}</el-descriptions-item>
          <el-descriptions-item label="操作工1">{{
            detail.userName1
          }}</el-descriptions-item>
          <el-descriptions-item label="操作者1作业时间">{{
            detail.userId1Time
          }} - {{ detail.userId1FinishTime }}</el-descriptions-item>
          <el-descriptions-item label="操作工2">{{
            detail.userName2
          }}</el-descriptions-item>
          <el-descriptions-item label="操作者2作业时间">{{
            detail.userId2Time
          }} - {{ detail.userId2FinishTime }}</el-descriptions-item>
          <el-descriptions-item label="操作工3">{{
            detail.userName3
          }}</el-descriptions-item>
          <el-descriptions-item label="操作者3作业时间">{{
            detail.userId3Time
          }} - {{ detail.userId3FinishTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{
            statusMap[detail.status]
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 编排工艺 -->
    <el-dialog title="编排工艺" width="450px" :visible.sync="arrangeModal.show">
      <div
        class="the-detail-dialog-content"
        style="max-height: 400px; height: auto;"
      >
        <el-form
          ref="craft"
          :model="arrangeModal.form"
          :rules="arrangeModal.rules"
        >
          <template v-for="(arrange, index) in arrangeModal.form.list">
            <el-form-item
              class="step-item"
              :key="'step' + arrange._id"
              :label="getStepText(index + 1)"
            ></el-form-item>
            <el-form-item
              :key="'craft' + arrange._id"
              label="工艺："
              :rules="arrangeModal.rules.craft"
              :prop="'list.' + index + '.craft'"
            >
              <el-select
                v-model="arrange.craft"
                @change="changeArrange(arrange._id, $event)"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in craftList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
              <el-button
                icon="el-icon-delete"
                size="mini"
                type="danger"
                :disabled="arrangeModal.form.list.length <= 1"
                @click="deleteArrange(arrange._id)"
              ></el-button>
            </el-form-item>
          </template>

          <el-form-item>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="addArrange"
            ></el-button>
          </el-form-item>

          <div class="dialog-footer">
            <el-button size="mini" @click="arrangeModal.show = false"
              >取 消</el-button
            >
            <el-button
              size="mini"
              type="primary"
              :loading="arrangeModal.loading"
              @click="confirmArrange"
              >确 定</el-button
            >
          </div>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="pdfUrlShow"
      title="图纸路径"
      @close="pdfUrlShow = false"
    >
      <el-form label-width="120px">
        <el-form-item label="图纸路径：">
          <div>
            <el-button
              v-for="(url, index) in pdfUrl"
              :key="index"
              style="text-align: left;"
              type="text"
            >
              <a
                :href="url"
                style="white-space: initial; word-break: break-all; word-wrap: break-word;"
                target="_blank"
                >{{ url }}</a
              >
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="工艺：">
          <div v-for="(item, index) in artFiles" :key="index">
            <a
              :href="item"
              style="
								color: #409eff;
								border-bottom: #409eff 1px solid;
							"
              target="_blank"
              >{{ item }}</a
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import user from "@/api/acl/user.js";
import { toChineseText } from "@/utils/index.js";
import ElDescriptions from "./el-descriptions.vue";
import ElDescriptionsItem from "./el-descriptions-item.vue";

const defaultQuery = () => ({
  innerCode: "",
  picCode: "",
  picName: "",
  page: 1,
  limit: 10
});
const defaultArrange = (step = 1) => ({
  _id: Date.now(),
  craft: "",
  step,
  productId: "",
  userId: "",
  userName: ""
});
export default {
  name: "engineering",

  components: {
    ElDescriptions,
    ElDescriptionsItem
  },

  data() {
    return {
      statusMapTab: {
        1: '未开始',
        21: '已派单',
        22: '已外协',
        23: '已派单-已外协',
        24: '供应商竣工',
        25: '已收货',
        26: '合格',
        27: '不合格',
        3: '生产中',
        4: '待品检',
        41: '报废',
        42: '可维修',
        43: '合格',
        44: '不合格',
        5: '品检中',
        51: '待入库',
        6: '入库中',
        7: '出库中',
        8: '已完成'
      },
      query: defaultQuery(),
      listLoading: false,
      list: [],
      total: 0,
      statusMap: {
        0: "未开始",
        1: "已开始",
        2: "已完成"
      },
      detailModal: {
        show: false,
        loading: false,
        productId: "",
        list: []
      },
      craftList: [],
      arrangeModal: {
        show: false,
        loading: false,
        form: {
          productId: "",
          list: [defaultArrange()]
        },
        rules: {
          craft: [
            {
              required: true,
              message: "请选择工艺",
              trigger: "change"
            }
          ]
        }
      },
      pdfUrl: "",
      pdfUrlShow: false,
      artFiles: []
    };
  },

  watch: {
    "arrangeModal.show": {
      immediate: true,
      handler(show) {
        if (show) {
          this.arrangeNameList();
        } else {
          if (this.$refs.craft) {
            this.arrangeModal.form.list = [defaultArrange()];
            this.$refs.craft.resetFields();
          }
        }
      }
    }
  },

  created() {
    this.getList();
  },

  methods: {
    // 设置其他信息
    changeArrange(_id, craft) {
      const { craftList } = this;
      const tcraft = craftList.find(item => item.name === craft);
      this.arrangeModal.form.list.forEach(item => {
        if (item._id === _id) {
          item.userId = tcraft.code;
          item.userName = tcraft.remark;
        }
      });
    },
    getStepText(index) {
      return "步骤" + toChineseText(index);
    },
    // 编排工艺
    arrageAction(row) {
      this.arrangeModal.form.productId = row.productId;
      this.arrangeModal.show = true;
      this.listCheckDetail(row.productId).then(list => {
        this.$set(
          this.arrangeModal.form,
          "list",
          list.length > 0
            ? list.map((item, index) => ({
                _id: item.id,
                craft: item.craft,
                step: index + 1,
                productId: item.productId,
                userId: item.chargemanId,
                userName: item.chargemanName
              }))
            : [defaultArrange()]
        );
      });
    },
    // 增加工艺
    addArrange() {
      this.$refs.craft.validate(valid => {
        if (valid) {
          let list = this.arrangeModal.form.list;
          this.arrangeModal.form.list.push(defaultArrange());
        }
      });
    },
    // 删除工艺
    deleteArrange(_id) {
      let index = this.arrangeModal.form.list.findIndex(
        item => item._id === _id
      );
      this.arrangeModal.form.list.splice(index, 1);
    },
    // 保存工艺
    confirmArrange() {
      this.$refs.craft.validate(valid => {
        if (valid) {
          this.arrangeModal.loading = true;
          this.arrangeSave();
        }
      });
    },
    // 查看详情
    showDetail(productId) {
      this.detailModal.productId = productId;
      this.detailModal.show = true;
      this.detailModal.loading = true;
      this.listCheckDetail(productId).then(list => {
        this.detailModal.list = list || [];
        this.detailModal.loading = false;
      });
    },
    // 获取详情接口
    listCheckDetail(productId) {
      return new Promise((resolve, reject) => {
        user
          .listCheckDetail({
            productId
          })
          .then(list => {
            resolve(list);
          })
          .catch(() => {
            this.detailModal.loading = false;
          });
      });
    },
    // 工艺名称列表
    arrangeNameList() {
      // 名称列表
      user.arrangeNameList().then(list => {
        this.craftList = list;
      });
    },
    // 删除操作
    detailAction(productId) {
      this.$alert("确定要删除工艺吗？", "删除工艺", {
        confirmButtonText: "确定",
        showCancelButton: true,
        callback: action => {
          if (action === "confirm") {
            user.deleteArrangeProduct([productId]).then(res => {
              this.getList();
              this.$message({
                showClose: true,
                message: "删除工艺操作成功",
                type: "success"
              });
            });
          }
        }
      });
    },
    // 编排工艺接口
    arrangeSave() {
      const { list, productId } = this.arrangeModal.form;
      const params = list.map((item, index) => ({
        craft: item.craft,
        productId,
        step: index + 1,
        userId: item.userId,
        userName: item.userName
      }));

      user
        .arrangeProduct(params)
        .then(res => {
          this.getList();
          this.$message({
            showClose: true,
            message: "编排工艺操作成功",
            type: "success"
          });
          this.arrangeModal.show = false;
          this.arrangeModal.loading = false;
        })
        .catch(err => {
          this.arrangeModal.loading = false;
        });
    },
    reset() {
      Object.assign(this.query, defaultQuery());
      this.getList();
    },
    selected() {
      this.getList();
    },
    fetchData(val) {
      this.query.page = val;
      this.getList();
    },
    getList() {
      this.listLoading = true;
      user.listProject(this.query).then(response => {
        debugger;
        this.listLoading = false;
        this.total = response.total;
        this.list =
            response.list.map(item => {
              item.statusName = this.statusMapTab[item.status || ''] || '--'
              return item
            })
        //this.list = response.list;
        // .map(item => {
        //   item.demandTime =
        //     (item.demandTime && timeFormat(new Date(item.demandTime))) || "--";
        //   item.purchaseTime =
        //     (item.purchaseTime && timeFormat(new Date(item.purchaseTime))) ||
        //     "--";
        //   return item;
        // });
      });
    },
    // 查看图纸
    seePaper(row) {
      user.listImageFolder(row).then(response => {
        if (response && response.imageUrl) {
          this.pdfUrl =
            typeof response.imageUrl === "string"
              ? [response.imageUrl]
              : response.imageUrl || [];
          this.pdfUrlShow = true;
          this.artFiles = response.artFiles;
        } else {
          this.$message.info("暂无图纸信息");
        }
      });
    }
  }
};
</script>

<style>
.step-item.el-form-item {
  margin-bottom: 0 !important;
}

.dialog-footer {
  text-align: right;
}

.the-detail-dialog-content {
  height: 400px;
  overflow-y: auto;
}
</style>
